//
//  oauthViewController.swift
//  SinaWeibo
//
//  Created by mac on 16/2/18.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class oauthViewController: UIViewController {
    
    //全局的webView
    let webView = UIWebView()
    //关闭控制器
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func testAccount(){
        //本地和webView交互
        let jsString = "document.getElementById('userId').value = '18749679269' , document.getElementById('passwd').value = 'zhang19911107' "
       //let jsString = "document.getElementById('userId').value = 'leiggee@126.com' , document.getElementById('passwd').value = 'oyonomg' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = UIColor.whiteColor()
        
        //手写代码时 根视图的背景颜色是透明的 .Plain平板样式
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        //测试账号
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "testAccount")
        loadOauthPage()
    }
    //在页面将要消失的时候 dismiss
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    //授权页面
    private func loadOauthPage(){
        let urlString =  "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
//extension扩建  处理webView的协议方法
extension oauthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        //开启指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭指示器
        SVProgressHUD.dismiss()
    }
    
    //获取收取成功后的code(授权码)
    //shouldStartLoadWithRequest 每次加载新的页面 都会重新发起一个request
    //协议方法 返回值 为 bool类型 一般返回 true 提供协议的对象才能够正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            //urlString 为空
            return false
        }
        
        //判断urlString中是否包含 code码
        if urlString.containsString("code") {
            //截取对应的code字符串
            //query 获取url的参数的字段和对应值
            guard let query = request.URL?.query else {
                return false
            }
            
            let codeStr = "code="
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            print(urlString,query,code)
            //用code码换取 token(令牌)
            //            loadAccessToken(code)
            
            AccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                //执行dismiss
                if isSuccess {
                    //登录成功
                    self.dismissViewControllerAnimated(true, completion: nil)
                    
                    //通知是同步还是异步的  同步的
                    //登录成功之后 将根视图控制器设置为 欢迎页面
                    NSNotificationCenter.defaultCenter().postNotificationName(KChoseRootVC, object: nil)
                    
                    print("come here oauth")
                } else {
                    //登录失败
                    SVProgressHUD.showErrorWithStatus("登录失败,请检查网络")
                }
                
            })
            return false  
        }
        return true
    }
}

